<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Market extends BaseModel
{
    /**
     * 行情中心
     */

    public function index($request){
        $whereMark = [];
        if (!empty($request['coin'])) {
            $whereMark['currency_mark'] = $request['coin'];
        }
        $whereMark['is_line'] = 1;
        $liCurrency = Currency::select('currency_id','currency_name','currency_logo','currency_mark')->where($whereMark)->orderBy('sort')->first();
        $wheretrade['currency_id'] = $liCurrency['currency_id'] ;
        //获取成交最大值
        $liCurrency['maxPrice'] = Trade::where($wheretrade)->max('price');
        //获取成交最小值
        $liCurrency['minPrice'] = Trade::where($wheretrade)->min('price');
        // 获取交易量
        $liCurrency['countNum'] = Trade::where($wheretrade)->sum('num');
        //最新价格
        $liCurrency['newPrice'] = $this -> getNewPriceByCurrencyid($liCurrency['currency_id']);
        $buyOrder['type'] = "buy";
        //获取买一价
        $liCurrency['buyPrice'] = $this->getOneOrdersByPrice($liCurrency['currency_id'], 'buy');
        //获取卖一价
        $liCurrency['sellPrice'] = $this->getOneOrdersByPrice($liCurrency['currency_id'], 'sell');
        //成交盘
        $Deal = Trade::where($wheretrade)->orderBy('add_time','desc')->take(30)->get();

        //买卖盘   买
        $sell = $this->getOrdersByType($liCurrency['currency_id'], 'buy', 20, 'desc');
        // 页面显示 成交量背景 比例
        foreach ($sell as $k=>$v){
            $sell[$k]->bili = 100-intval(($v->trade_num/$v->num)*100)."%";
        }
        //买卖盘   卖
        $buy = $this->getOrdersByType($liCurrency['currency_id'], 'sell', 20, 'asc');
        $buy=  array_reverse($buy);
        // 页面显示 成交量背景 比例
        foreach ($buy as $k=>$v){
            $buy[$k]->bili = 100-intval(($v->trade_num/$v->num)*100)."%";
        }
        //查询其他交易币  去掉当前 币种
//        $where['currency_id'] =  array('NEQ',$liCurrency['currency_id']);
        $where['is_line'] = 1;
        $listCurrency = Currency::select('currency_id','currency_name','currency_logo','currency_mark')->where($where)->where('currency_id','!=',$liCurrency['currency_id'])->get();
        foreach($listCurrency as $k =>$v){
            $listCurrency[$k]['newPrice'] = $this -> getNewPriceByCurrencyid($v['currency_id']);
        }
        $count = max(count($sell),count($buy))? count($sell):count($buy);
        return [$Deal,$sell,$listCurrency,$liCurrency,$buy,$count];
    }


    public function getMarket($request){
//        $where['status'] = array('in',array(0,1));
        $list = Orders::select('price')->whereIn('status',[0,1])->groupBy('price')->get();
        $price_arr = [];
        $buy_arr = [];
        $sell_arr = [];
        foreach ($list as $k=>$v){
            $sell = Orders::select(DB::raw('sum(num) as num'))->whereIn('status',[0,1])->where(['type'=>'sell','price'=>$v['price']])->get();
            $buy = Orders::select(DB::raw('sum(num) as num'))->whereIn('status',[0,1])->where(['type'=>'buy','price'=>$v['price']])->get();
            $list[$k]['sell'] = !empty($sell[0]['num'])?$sell[0]['num']:0;
            $list[$k]['buy'] = !empty($buy[0]['num'])?$buy[0]['num']:0;
        }
        foreach ($list as $k=>$v){
            $price_arr[] = floatval($v['price']);
            $sell_arr[] = floatval($v['sell']);
            $buy_arr[] = floatval($v['buy']);
        }
        $data['price'] = $price_arr;
        $data['sell'] = $sell_arr;
        $data['buy'] = $buy_arr;
        return $data;
    }


    /**
     *  获取最新交易价格
     * @param unknown $type    币种id
     * @return unknown|number
     */
    public function getNewPriceByCurrencyid($currency_id){
        $where['currency_id'] = $currency_id;
        $list = Orders::where($where)->select('price')->orderBy('add_time','desc')->first();
        if(!empty($list)){
            return $list['price'];
        }else{
            return  0;
        }
    }

    /**
     * 获取一个挂单记录价格 买一 卖一
     * @param unknown $currencyid
     * @param unknown $type
     * @param unknown $order
     */
    protected function getOneOrdersByPrice($currencyid,$type){
        $where['currency_id'] = $currencyid;
        $where['type'] = $type;
//        $where['status'] = array('in',array(0,1));
        switch ($type){
            case 'buy': $order='desc';
                break;
            case 'sell':$order='asc';
                break;
        }
        $orders= Orders::where($where)->whereIn('status',[0,1])->select('price')->orderBy('price',$order)->first();
        return $orders['price'];
    }

    /**
     * 返回指定数量排序的挂单记录
     * @param char $type buy sell
     * @param int $num 数量
     * @param char $order 排序 desc asc
     */
    protected function getOrdersByType($currencyid,$type,$num,$order){
//        $where['type'] = array('eq',$type);
        $where['type'] = $type;
//        $where['status'] = array('in',array(0,1));
        $where['currency_id'] = $currencyid;
        $list= DB::table('orders')->select(DB::raw('sum(num) as num,sum(trade_num) as trade_num,price,type,status'))->where($where)->whereIn('status',[0,1])->groupBy('price')->orderBy('price',$order)->orderBy('add_time','asc')->take($num)->get();
        foreach ($list as $k=>$v){
            $list[$k]->bili = 100-($v->trade_num/$v->num*100);
        }
        if ($type=='sell'){
            $list=  array_reverse($list);
        }
        return $list;
    }

}
